<template>
  <div class="company-pie-chart">
    <div ref="chartRef" class="chart-container"></div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import request from "@/utils/request";

export default {
  name: "CompanyPieChart",
  data() {
    return {
      chart: null,
      chartData: [
        { value: 1048, name: "Search Engine" },
        { value: 735, name: "Direct" },
        { value: 580, name: "Email" },
        { value: 484, name: "Union Ads" },
        { value: 300, name: "Video Ads" },
      ],
    };
  },
  props: {
    period: {
      type: String,
      default: "month",
    },
  },
  mounted() {

    // this.getChartData();
  },
  watch: {
    period: {
      handler(newVal, oldVal) {
        this.getChartData();
      },
      immediate: true,
    },
  },
  methods: {
    getChartData() {
      request({
        url: "/zk/substation/devices-by-substation-type",
        params: {
          dimension: this.period,
        },
        method: "get",
      }).then((res) => {
        console.log("result", res);
        this.renderChart(res.data);
      });
    },
    renderChart(data) {
      // 提取所有时间点（去重+排序）
      const timeKeys = [...new Set(data.map((item) => item.timeKey))].sort(
        (a, b) => {
          // 简单排序：年/月/周格式天然可字典序排序
          return a.localeCompare(b);
        }
      );

      // 按 dictLabel 分组
      const seriesMap = {};
      data.forEach((item) => {
        const label = item.dictLabel || item.type || "未知类型";
        if (!seriesMap[label]) {
          seriesMap[label] = {};
        }
        seriesMap[label][item.timeKey] = item.count;
      });

      const series = Object.keys(seriesMap).map((label) => ({
        name: label,
        type: "line",
        smooth: true,
        symbol: "circle",
        data: timeKeys.map((t) => seriesMap[label][t] || 0),
      }));

      const option = {
        // title: {
        //   text: "变电站新增数量趋势",
        //   textStyle: {
        //     color: "#FFFFFF",
        //   },
        // },
        tooltip: { trigger: "axis" },
        legend: {
          data: Object.keys(seriesMap),
          bottom: 0,
          textStyle: { color: "#fff" },
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "15%",
          top: "20%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          data: timeKeys,
          axisLine: { lineStyle: { color: "#fff" } },
          axisLabel: { color: "#fff" },
        },
        yAxis: {
          type: "value",
          name: "数量",
          axisLine: { lineStyle: { color: "#fff" } },
          axisLabel: { color: "#fff" },
        },
        series,
      };

      if (!this.chart) {
        this.chart = echarts.init(this.$refs.chartRef);
      }
      this.chart.setOption(option);
    },
    initChart(param) {
      this.chart = echarts.init(this.$refs.chartRef);
      const option = {
        title: {
          text: "",
          left: "center",
          textStyle: {
            color: "#FFFFFF",
          },
        },
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b}设备数量: {c} ({d}%)",
          textStyle: {
            color: "#FFFFFF",
          },
        },
        legend: {
          orient: "vertical",
          left: "left",
          data: param.map((item) => item.dict_label),
          textStyle: {
            color: "#FFFFFF",
          },
        },
        color: ["#5470C6", "#91CC75", "#FAC858", "#EE6666", "#73C0DE"], // Use brighter colors for the pie chart
        series: [
          {
            name: "Data Sources",
            type: "pie",
            radius: "50%",
            data: param.map((item) => ({
              value: item.value,
              name: item.dict_label,
            })),
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)",
              },
            },
            label: {
              color: "#FFFFFF",
              formatter: "{b}设备数量 ", // Display device quantity in labels
            },
            labelLine: {
              lineStyle: {
                color: "#FFFFFF",
              },
            },
          },
        ],
      };
      this.chart.setOption(option);

      // Responsive adjustment
      window.addEventListener("resize", this.handleResize);
    },
    handleResize() {
      if (this.chart) {
        this.chart.resize();
      }
    },
  },
  beforeDestroy() {
    if (this.chart) {
      window.removeEventListener("resize", this.handleResize);
      this.chart.dispose();
    }
  },
};
</script>

<style scoped lang="scss">
.company-pie-chart {
  width: 100%;
  height: 100%;
}

.chart-container {
  height: 243px;
  width: 100%;
  margin: 0 auto;
  padding: 10px;
}
</style>
